package com.imax.center;

import com.imax.center.service.DeviceDataService;
import com.imax.center.tcp.ClientHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 应用程序初始化器
 * 在应用启动时执行一些初始化操作
 */
@Slf4j
@Component
public class AppInitializer implements CommandLineRunner {

    @Value("${tcp.server.port}")
    private int tcpPort;

    @Autowired
    private DeviceDataService deviceDataService;

    @Override
    public void run(String... args) {
        log.info("开始监听Tcp服务");
        this.listenTcpServer(); //需要放到最后
    }

    public void listenTcpServer() {
        try (ServerSocket serverSocket = new ServerSocket(tcpPort)) {
            log.info("Tcp Server is listening on port " + tcpPort);
            while (true) {
                Socket socket = serverSocket.accept();
                // 处理客户端TCP请求
                new ClientHandler(socket, deviceDataService).start();
            }
        } catch (IOException ex) {
            log.error("Error on creating server socket", ex);
        }
    }

} 